package com.gt.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.admin.domain.MenuSecond;
import com.gt.admin.mapper.MenuSecondMapper;
import com.gt.admin.service.IMenuSecondService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 二级目录service
 */
@Service
public class MenuSecondServiceImpl extends ServiceImpl<MenuSecondMapper, MenuSecond> implements IMenuSecondService {
    @Autowired
    private MenuSecondMapper menuSecondMapper;

    @Override
    public List<MenuSecond> selectList(MenuSecond menuSecond) {
        LambdaQueryWrapper<MenuSecond> queryWrapper = Wrappers.lambdaQuery(menuSecond);
        queryWrapper.orderByAsc(MenuSecond::getSort);
        return list(queryWrapper);
    }

    /**
     * 构建前端所需要树结构
     * @param menus
     * @return
     */
    @Override
    public List<MenuSecond> buildMenuTree(List<MenuSecond> menus) {
        List<MenuSecond> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (MenuSecond menuSecond : menus) {
            tempList.add(menuSecond.getMenuId());
        }
        for (Iterator<MenuSecond> iterator = menus.iterator(); iterator.hasNext();) {
            MenuSecond menuSecond = (MenuSecond) iterator.next();
            if(!tempList.contains(menuSecond.getParentId())){
                recursionFn(menus, menuSecond);
                returnList.add(menuSecond);
            }
        }if (returnList.isEmpty()){
            returnList = menus;
        }return returnList;
    }

    /**
     * 得到子节点列表
     */
    private List<MenuSecond> getChildList(List<MenuSecond> list, MenuSecond t){
        List<MenuSecond> tlist = new ArrayList<>();
        Iterator<MenuSecond> it = list.iterator();
        while (it.hasNext()){
            MenuSecond n = (MenuSecond) it.next();
            if(n.getParentId().longValue() == t.getMenuId().longValue()){
                tlist.add(n);
            }
        }return tlist;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<MenuSecond> list, MenuSecond t){
        List<MenuSecond> childList = getChildList(list, t);
        t.setChildList(childList);
        for (MenuSecond tChild : childList){
            if(hasChild(list, tChild)){
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MenuSecond> list,MenuSecond t){
        return getChildList(list,t).size()>0;
    }
}
